package queenattack

import (
	"fmt"
	"math"
	"strconv"
)

const testVersion = 2

type CanQueenAttackError struct {
}

func (e *CanQueenAttackError) Error() string {
	return fmt.Sprintf("can't attack")
}

// CanQueenAttack
func CanQueenAttack(black, white string) (attack bool, err error) {
	bX, bY, wX, wY, r := isValid(black, white)
	if !r {
		err = &CanQueenAttackError{}
		return
	}

	if bX == wX || bY == wY {
		attack = true
		return
	}

	bYLength, _ := strconv.Atoi(bY)
	wYLength, _ := strconv.Atoi(wY)
	yLength := bYLength - wYLength
	xLength := int([]rune(bX)[0]) - int([]rune(wX)[0])

	if math.Abs(float64(xLength)) == math.Abs(float64(yLength)) {
		attack = true
		return
	}

	return
}

// isValid
func isValid(black, white string) (bX, bY, wX, wY string, ok bool) {
	if black == white || (black == "" || white == "") || (len(black) != 2 || len(white) != 2) {
		ok = false
		return
	}

	bX, bY = black[:1], black[1:2]
	wX, wY = white[:1], white[1:2]

	if (bX < "a" || bX > "h") || (wX < "a" || wX > "h") {
		ok = false
		return
	}

	if (bY < "1" || bY > "8") || (wY < "1" || wY > "8") {
		ok = false
		return
	}

	ok = true
	return
}
